<template>
  <div class="container p-6">
    <!-- 搜索区域 -->
    <div class="mb-4 flex items-center space-x-4">
      <el-input
        label="题库名称"
        v-model="searchParams.title"
        placeholder="题库名称"
        class="!w-[200px]"
        clearable
        @input="handleAutoSearch"
        @clear="handleAutoSearch"
        size="large"
      />
      <el-button type="primary" @click="handleAdd" size="large">添加</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table v-loading="loading" :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="序号" min-width="80" align="center" />
      <el-table-column
        prop="title"
        label="题库名称"
        min-width="140"
        align="center"
      />
      <el-table-column
        prop="userName"
        label="创建人"
        min-width="120"
        align="center"
      >
        <template #default="scope">{{
          scope.row.userName || 'admin'
        }}</template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        min-width="180"
        align="center"
      />

      <el-table-column label="是否启用" min-width="120" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isDeleted"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        fixed="right"
        min-width="120"
        align="center"
      >
        <template #default="scope">
          <!-- <el-button type="danger" link @click="handleDelete(scope.row)">
            删除
          </el-button> -->
          <el-button type="primary" link @click="handleEdit(scope.row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="mt-4 flex items-center text-sm text-gray-500">
      <span>共 {{ searchParams.total }} 条</span>
      <div class="ml-4 flex items-center">
        <el-select
          v-model="searchParams.pageSize"
          class="!w-[100px] mr-2"
          @change="handleSizeChange"
        >
          <el-option
            v-for="size in [10, 20, 30, 50]"
            :key="size"
            :label="`${size}条/页`"
            :value="size"
          />
        </el-select>
        <el-pagination
          v-model:current-page="searchParams.pageNum"
          :page-size="searchParams.pageSize"
          layout="prev, pager, next"
          :total="searchParams.total"
          :pager-count="5"
          background
          @current-change="handleCurrentChange"
        />
        <span class="mx-2">前往</span>
        <el-input
          v-model="jumpPage"
          class="!w-[50px]"
          @keyup.enter="handleJumpPage"
        />
        <span class="mx-2">页</span>
      </div>
    </div>

    <!-- 添加/编辑题库侧边栏 -->
    <el-drawer
      v-model="dialogVisible"
      :title="isEditMode ? '编辑题库' : '添加题库'"
      :modal="true"
      size="350px"
      :close-on-click-modal="false"
      direction="rtl"
      destroy-on-close
    >
      <template #default>
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          class="drawer-form"
        >
          <el-form-item label="题库名称" prop="title">
            <el-input v-model="form.title" placeholder="题库名称" />
          </el-form-item>
          <el-form-item label="是否开启刷题">
            <el-switch
              v-model="form.isExercise"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div class="drawer-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getRepoInfo,
  addrepo,
  deleteRepo,
  editRepo,
} from '@/api/teacher/question'
import { useUserStore } from '@/store/modules/user'

// 用户store
const userStore = useUserStore()

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 用户信息
const userInfo = userStore.userInfo

// 分页相关
const searchParams = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 10,
  title: '',
})

// 后续需要替换为真实API
// API函数
const getRepoList = async () => {
  if (loading.value) return
  loading.value = true
  try {
    const {
      data: { records, total, current, size },
    } = await getRepoInfo(searchParams)
    tableData.value = records
    searchParams.total = total
    searchParams.pageNum = current
    searchParams.pageSize = size
  } catch (error) {
    ElMessage.error('获取题库列表失败')
  } finally {
    loading.value = false
  }
}

const addRepo = async (data) => {
  const { code, msg } = await addrepo(data)
  if (code == 1) {
    ElMessage.success('添加成功')
    getRepoList()
  }
}

const delRepo = async (id) => {
  const { code, msg } = await deleteRepo(id)
  if (code == 1) {
    ElMessage.success('删除成功')
    getRepoList()
  }
}

// 防抖定时器
let searchTimer = null

// 弹窗显示控制
const dialogVisible = ref(false)
const isEditMode = ref(false)
const currentEditId = ref('')
// 表单ref
const formRef = ref()

// 表单数据
const form = reactive({
  title: '',
  isExercise: 0,
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入题库名称', trigger: 'blur' }],
}

// 处理搜索
const handleSearch = () => {
  getRepoList()
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该题库吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code, msg } = await delRepo(row.id)
      if (code == 0) {
        ElMessage.error('删除失败：' + msg)
        return
      }
      getRepoList()
      ElMessage.success('删除成功')
    })
    .catch(() => {
      // 取消删除
    })
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  searchParams.pageSize = val
  getRepoList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  searchParams.pageNum = val
  getRepoList()
}

// 处理跳转页码
const jumpPage = ref('')
const handleJumpPage = () => {
  searchParams.pageNum = Number(jumpPage.value)
  getRepoList()
}

// 打开添加弹窗
const handleAdd = () => {
  isEditMode.value = false
  dialogVisible.value = true
  form.title = ''
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 处理编辑
const handleEdit = (row) => {
  isEditMode.value = true
  currentEditId.value = row.id
  dialogVisible.value = true
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.title = row.title
  form.isExercise = row.isExercise || 0
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      // 提交到后端的逻辑
      const newRepo = {
        ...form,
        userId: userInfo.id,
      }
      // 判断是否是编辑
      const { code, msg } = isEditMode.value
        ? await editRepo({ ...newRepo, id: currentEditId.value })
        : await addRepo(newRepo)
      if (code == 0) {
        ElMessage.error((isEditMode.value ? '编辑' : '添加') + '失败：' + msg)
        return
      }

      ElMessage.success((isEditMode.value ? '编辑' : '添加') + '成功')
      dialogVisible.value = false
      // 刷新表格数据
      getRepoList()
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 自动搜索处理函数（添加防抖）
const handleAutoSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  // 增加防抖时间到500ms
  searchTimer = setTimeout(() => {
    getRepoList()
  }, 500)
}

// 处理状态切换
const handleStatusChange = async (row) => {   
  const newStatus = row.isDeleted == 0 ? 0 : 1
  const { code, msg } = await editRepo({
    title: row.title,
    isDeleted: newStatus,
    id: row.id,
  })
  if (code == 1) {
    ElMessage.success('状态修改成功')
    getRepoList()
  } else {
    ElMessage.error('状态修改失败：' + msg)
    return
  }
    
}

// 挂载
onMounted(() => {
  // 获取题库信息
  getRepoList()
})
</script>

<style lang="less" scoped>
.container {
  background-color: white;
  border-radius: 8px;
  min-height: calc(100vh - 120px);
}

:deep(.el-table) {
  .cell {
    display: flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
  }

  .el-table__header th {
    .cell {
      justify-content: center;
    }
  }

  .el-button {
    margin: 0 auto;
  }
}

// 上传区域样式
:deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px dashed #e6e6e6;
  border-radius: 8px;

  &:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon--upload {
    font-size: 48px;
    color: #909399;
    margin-bottom: 12px;
  }

  .upload-text {
    color: #606266;
    font-size: 14px;
    text-align: center;

    .text-primary {
      color: var(--el-color-primary);
      cursor: pointer;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
}

// 分页样式
:deep(.el-pagination) {
  .el-pagination__total {
    margin-right: 16px;
  }

  .el-pagination__sizes {
    margin-right: 16px;
  }

  .el-pager li {
    background-color: transparent;

    &.is-active {
      background-color: var(--el-color-primary);
      color: white;
    }
  }

  .btn-prev,
  .btn-next {
    background-color: transparent;
  }

  .el-input__inner {
    text-align: center;
    padding: 0 5px;
  }
}

// 下拉选择框样式
:deep(.el-select) {
  .el-input__wrapper {
    background-color: transparent;
  }
}

:deep(.el-form) {
  .el-form-item {
    margin-bottom: 20px;
  }
}

// 抽屉表单样式
:deep(.el-drawer__body) {
  padding: 20px;

  .drawer-form {
    height: calc(100% - 60px);
    overflow-y: auto;
  }
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 20px;
  background: white;
  border-top: 1px solid var(--el-border-color-lighter);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
